<script setup>
import { computed } from 'vue'
import { defineProps } from 'vue'
import { useRouter } from 'vue-router'
import SvgIcon from '@/components/svg-icon/index.vue'
import axios from 'axios'
import { ref, watch } from 'vue'
import {record_route, search_point} from "@/api/mock/index.js";
const props = defineProps({
  keyword: String
})

const allResults = ref([])
const router = useRouter()
async function fetchResults(kw) {


  try {
    console.log('开始搜索:', kw)
    const response = await search_point(kw)
    console.log('原始响应数据:', response)
    
    // 打印后端返回的完整数据
    console.log('后端传送来的搜索结果:', response.data)
    
    if (Array.isArray(response.data)) {
      allResults.value = response.data
      console.log('搜索结果数组:', allResults.value)
    } else {
      console.warn('接口返回非数组数据:', response)
      allResults.value = []
    }

  } catch (error) {
    console.error('搜索失败:',  error)
    allResults.value = []
  }




  // fetch(url, {
  //   method: 'POST',
  //   headers,
  //   body,
  //   credentials: 'include' // 可选：跨域携带凭证
  // })
  //     .then(response => {
  //       if (!response.ok) {
  //         throw new Error(`HTTP 错误: ${response.status}`)
  //       }
  //       return response.json()
  //     })
  //     .then(data => {
  //       // 确保返回数据是数组
  //       if (Array.isArray(data.data)) {
  //         allResults.value = data.data
  //         console.log(allResults.value)
  //       } else {
  //         console.warn('接口返回非数组数据:', data)
  //         allResults.value = []
  //       }
  //     })
  //     .catch(err => {
  //       console.error('搜索失败:', err)
  //       allResults.value = []
  //     })
}
// 新增点击事件处理函数
const handleItemClick = async (item) => {
  let start_id;

  start_id = localStorage.getItem('currentRoomDoorNum')

  try {
    await record_route(start_id, item.id)
  } catch (error) {
    console.error('记录导航失败:', {
      error: error.message,
      status: error.response?.status,
      data: error.response?.data
    })
  }

  await router.push(`/?id=${start_id}&&targetId=${item.id}&targetFloor=F${item.floor}`)
  window.location.reload()
}

watch(
    () => props.keyword,
    (newKeyword) => {
      if (newKeyword?.trim()) {
        fetchResults(newKeyword.trim())
        console.log(`正在搜索：${newKeyword.trim()}`)
      }
    },
    { immediate: true } // 立即触发一次初始搜索
)



const filteredResults = computed(() => {
  if (!props.keyword?.trim()) return []

  // 创建模糊匹配模式，将关键词中的每个字符用.*分隔，实现...校...办...的效果
  const createFuzzyPattern = (str) => {
    // 直接在每个字符之间插入.*，不考虑特殊字符转义
    return str.split('').join('.*')
  }

  const pattern = createFuzzyPattern(props.keyword.trim())
  const regex = new RegExp(pattern, 'i') // 不区分大小写匹配

  console.log("------------------------------pattern", pattern)

  return allResults.value.filter(item =>
      (item.name && regex.test(item.name)) ||
      (item.room_code && regex.test(item.room_code)) ||
      (item.id && regex.test(item.id)) ||
      (item.floor && regex.test(item.floor)) ||
      (item.staff && regex.test(item.staff)) ||
      (item.remark && regex.test(item.remark)) ||
      (item.department && regex.test(item.department))
  )
})

</script>

<template>
  <div>
    <div v-if="filteredResults.length" class="result-list">
      <div class="result-item" v-for="(item, idx) in filteredResults" :key="idx" @click="handleItemClick(item)">
        <div class="result-info">
          <div class="result-header">
            <div class="result-title">{{ item.name }}</div>
<!--            <span class="result-tag">{{ item.type }}</span>-->
          </div>
          <div class="result-details">
            <div class="result-desc">
              <van-icon name="location-o" class="loc-icon" />
              <span class="result-doorNum">{{ item.room_code }}</span>
              <span class="separator">|</span>
<!--              <span class="result-id">ID: {{ item.id }}</span>-->
<!--              <span class="separator">|</span>-->
              <span class="result-floor">{{ item.floor }}F</span>
            </div>
            <div v-if="item.staff || item.department || item.remark" class="additional-info">
              <span v-if="item.staff" class="result-staff">{{ item.staff }}</span>
              <span v-if="item.department" class="result-department">{{ item.department }}</span>
              <span v-if="item.remark" class="result-remark">{{ item.remark }}</span>
            </div>
          </div>
        </div>
        <div class="result-action">
          <div class="nav-btn">
            <svg-icon name="plane" class="home-icon" />
          </div>
        </div>
      </div>
    </div>
    <div v-else style="color: #aaa; text-align: center; margin-top: 32px; font-size: 16px;">暂无搜索结果</div>
  </div>
</template>

<style scoped>
.result-list {
  margin-top: 8px;
}

.result-item {
  display: flex;
  align-items: center;
  padding: 16px 12px 16px 16px;
  border-bottom: 1px solid #f5f5f5;
  background: #fff;
  transition: background-color 0.2s;
}

.result-item:hover {
  background-color: #f9f9f9;
}

.result-info {
  flex: 1;
  min-width: 0;
}

.result-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 6px;
}

.result-title {
  font-size: 17px;
  font-weight: 500;
  color: #222;
  flex: 1;
  margin-right: 10px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.result-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.result-desc {
  display: flex;
  align-items: center;
  font-size: 13px;
  color: #666;
  flex-wrap: wrap;
  gap: 4px;
}

.loc-icon {
  margin-right: 2px;
  font-size: 14px;
  color: #888;
}

.separator {
  color: #ccc;
  margin: 0 2px;
}

.result-doorNum,
.result-id,
.result-floor {
  white-space: nowrap;
}

.result-tag {
  display: inline-block;
  background: #e8f4ff;
  color: #1976d2;
  font-size: 12px;
  border-radius: 4px;
  padding: 2px 8px;
  flex-shrink: 0;
}

.additional-info {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  font-size: 12px;
  color: #888;
}

.result-staff,
.result-department,
.result-remark {
  background: #f5f5f5;
  padding: 2px 6px;
  border-radius: 3px;
}

.result-action {
  display: flex;
  align-items: center;
  margin-left: 10px;
  flex-shrink: 0;
}

.nav-btn {
  width:  40px;
  height: 40px;
  background: #2196f3;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: transform 0.2s;
}

.nav-btn:hover {
  transform: scale(1.05);
}

.home-icon {
  color: white;
  font-size: 18px;
}
</style>
